///<reference path="../typings/tsd.d.ts" />
/*使用说明
该功能用于在右下角的空间创建一个tab区域。可以add、remove，removeall等功能方法
$tab=$('#tab').tabpanel()   $tab.tabpanel("add",opt:ITabPanelInfo)
*/
/** tabpanel参数*/
interface ITabPanelInfo {
    id: string;
    title?: string;
    url?: string;
}
module AUTO {
    export class TabPanel {
        /*样式添加：外层autotabpanel，标签 tab-tabs  主体页面 tab-content 标签页tab-pane  菜单tab-menus  */
        private static DefaultClassName = "autotabpanel";
        private static DefaultEventName = ".autotabpanelEvent";
        private static OutDom = '<ul class="nav nav-tabs tab-tabs"></ul><div class="tab-content"></div>';
        private static TabLi = _.template('<li><a href="#<%=id%>" data-toggle="tab" data-id="<%=id%>"><%=title%>&nbsp;<button type="button" class="close" ><span>&times;</span></button></a></li>');
        private static TabContent = _.template('<div class="tab-pane" id="<%=id%>"><iframe allowfullscreen="" scrolling="auto" style="width:100%;height:100%;" src="<%=url%>" frameborder="0"></iframe></div>');
        private static TabMenu = `<div class="dropdown tab-menus">
   <ul class="dropdown-menu">
    <li><a href="#" data-close="me">关闭</a></li>
    <li class="divider"></li>
    <li><a href="#" data-close="right">关闭右侧标签页</a></li>
    <li><a href="#" data-close="left">关闭左侧标签页</a></li>
    <li><a href="#" data-close="other">关闭其它标签页</a></li>
    <li><a href="#" data-close="all">全部关闭</a></li>
  </ul>
</div>`;
        private $el: JQuery;
        private _cmd = {
            add: this.AddTab,
            remove: this.RemoveTab,
            removeall: this.RemoveallTab
        };
        /**保存添加过的id */
        private idList: string[];
        /**保存激活的顺序 */
        private seqList: string[];
        /**标签ul */
        private tabUL: JQuery;
        /**标签上的menu */
        private tabMenu: JQuery;
        /**标签content 的div*/
        private tabContent: JQuery;
        constructor(element: Element, cmd?: string, tabInfo?: ITabPanelInfo) {
            this.$el = $(element);
            if (_.isUndefined(cmd)) {
                this.init();
                this.bindEvent();
            } else {
                let me: TabPanel = this.$el.data("OriginData");
                me._cmd[cmd].call(me, tabInfo);
            }
        }
        private init() {
            this.idList = [];
            this.seqList = [];
            this.$el.addClass(TabPanel.DefaultClassName)
                .html(TabPanel.OutDom + TabPanel.TabMenu);
            /**获取UL标签及菜单,内容 */
            this.tabUL = this.$el.find("ul.tab-tabs");
            this.tabMenu = this.$el.find("div.tab-menus");
            this.tabContent = this.$el.find("div.tab-content");
            this.$el.data("OriginData", this);
        }
        //绑定事件
        private bindEvent() {
            let scope = this;
            this.$el.off(TabPanel.DefaultEventName);
            $(window).off(TabPanel.DefaultEventName);
            this.$el.on("click" + TabPanel.DefaultEventName, ".close", function () {
                scope.RemoveTab({ id: $(this).parent().data("id") });
            });
            //默认元素要填充最下方
            $(window).on("resize" + TabPanel.DefaultEventName, function (event) {
                scope.$el.height($(window).height() - scope.$el.offset().top);
            }).trigger("resize");
            //激活时，插入到激活列表中
            this.$el.on('show.bs.tab', 'a[data-toggle="tab"]', function (e) {
                scope.seqList.push($(this).data("id"));
            });
            //在标签页上点右键，弹出菜单
            this.$el.on("contextmenu" + TabPanel.DefaultEventName, ".tab-tabs li", function (event) {
                var $li = $(this);
                var offset = $li.position();
                scope.tabMenu.css({
                    "left": event.offsetX + offset.left,
                    "top": scope.tabUL.height()
                }).find(".dropdown-menu").show();
                //获取到当前标签的id,绑定到tabMenu上去。
                scope.tabMenu.data("select_id", $li.find("a").data("id"));
                return false;
            });
            /*点击关闭按钮时*/
            this.$el.on("click" + TabPanel.DefaultEventName, ".tab-menus a[data-close]", function (event) {
                let flag = $(this).data("close");
                let id = scope.tabMenu.data("select_id").toString(); //强制转成字符，因为idList中存放的字符。
                //索引
                let idx = scope.idList.indexOf(id);
                if (idx > -1) {
                    switch (flag) {
                        case "me":
                            scope.RemoveTab({ id });  //ts的缩写方式
                            break;
                        case "right":
                            var toRemove = scope.idList.slice(idx + 1);
                            _.each(toRemove, function (rId) {
                                scope.RemoveTab({ id:rId });
                            });
                            break;
                        case "left":
                            var toRemove = scope.idList.slice(0,idx);
                            _.each(toRemove, function (rId) {
                                scope.RemoveTab({ id: rId });
                            });
                            break;
                        case "other":
                            var toRemove = scope.idList.concat([])
                            _.each(toRemove, function (rId) {
                                rId!=id&&scope.RemoveTab({ id: rId });
                            });
                            break;
                        case "all":
                            scope.RemoveallTab();
                            break;
                    }
                }
                //隐藏菜单
                scope.tabMenu.find(".dropdown-menu").hide();
            });
            /**点击标签栏其它地方，关闭菜单*/
            this.$el.on("click" + TabPanel.DefaultEventName, ".tab-tabs", function (event) {
                scope.tabMenu.find(".dropdown-menu").hide();
            });
        }
        /**添加新标签页 */
        private AddTab(tabInfo: ITabPanelInfo) {
            let idx = this.idList.indexOf(tabInfo.id);
            if (idx >= 0) {
                this.tabUL.find("li>a").eq(idx).tab("show");
                return;
            }
            this.tabUL.append(TabPanel.TabLi(tabInfo));
            this.tabContent.append(TabPanel.TabContent(tabInfo));
            this.idList.push(tabInfo.id);
            this.tabUL.find("li>a").last().tab("show");
        }
        /**删除标签页 */
        private RemoveTab(tabInfo: ITabPanelInfo) {
            let idx = this.idList.indexOf(tabInfo.id);
            if (idx >= 0) {
                let $li = this.tabUL.find(`li:eq(${idx})`);
                let isActive = $li.hasClass("active");
                //移除标签，内容页及id索引
                $li.remove();
                this.$el.find(`#${tabInfo.id}`).remove(); //移除内容页
                this.idList.splice(idx, 1);
                //如果关闭页是激活页，则激活前一个有效的id
                while (isActive && this.seqList.length > 0) {
                    let lastid = this.seqList.pop();
                    let i = this.idList.indexOf(lastid);
                    if (i >= 0) {
                        this.tabUL.find("li>a").eq(i).tab("show");
                        break;
                    }
                }
            }
        }
        /**全部删除 */
        private RemoveallTab() {
            this.init();
            this.bindEvent();
        }
    }
}